package com.rxt.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rxt.common.result.Result;
import com.rxt.model.domain.KKonwledge;
import com.rxt.mapper.KKonwledgeMapper;
import com.rxt.model.domain.UExpert;
import com.rxt.model.domain.UUser;
import com.rxt.model.dto.KKonwledgeDto;
import com.rxt.model.dto.KRemarkDto;
import com.rxt.model.dto.UUserDto;
import com.rxt.model.vo.KKonwledgePageVo;
import com.rxt.model.vo.KKonwledgeVo;
import com.rxt.service.IKKonwledgeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxt.service.IKRemarkService;
import com.rxt.service.IUExpertService;
import com.rxt.service.IUUserService;
import com.rxt.util.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 周梓文
 * @since 2023-08-24
 */
@Service
public class KKonwledgeServiceImpl extends ServiceImpl<KKonwledgeMapper, KKonwledge> implements IKKonwledgeService {

    @Autowired
    private IKRemarkService remarkService;

    @Autowired
    private IUUserService iuUserService;

    @Autowired
    private IUExpertService iuExpertService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public Result getPage(KKonwledgePageVo kKonwledgeVo) {
        String keyWord = kKonwledgeVo.getKeyWord();

        Page<KKonwledge> page = new Page<>(kKonwledgeVo.getPage(), kKonwledgeVo.getPageSize());

        LambdaQueryWrapper<KKonwledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(!StrUtil.isEmptyIfStr(keyWord), KKonwledge::getTitle,keyWord)
                .or(!StrUtil.isEmptyIfStr(keyWord))
                .like(!StrUtil.isEmptyIfStr(keyWord), KKonwledge::getContent,keyWord)
                .orderByDesc(KKonwledge::getCreateTime);

        this.page(page, lambdaQueryWrapper);

        List<KKonwledgeDto> collect = page.getRecords().stream().map((item) -> {
            KKonwledgeDto kKonwledgeDto = new KKonwledgeDto();
            BeanUtils.copyProperties(item, kKonwledgeDto);

            Long authorId = item.getUserId();
            UExpert author = iuExpertService.getOne(new LambdaQueryWrapper<UExpert>().eq(UExpert::getUserId, authorId));
            kKonwledgeDto.setAuthor(author);
            return kKonwledgeDto;
        }).collect(Collectors.toList());

        Page<KKonwledgeDto> kKonwledgeDtoPage = new Page<>();
        kKonwledgeDtoPage.setRecords(collect);
        kKonwledgeDtoPage.setTotal(page.getTotal());

        return Result.ok(kKonwledgeDtoPage);
    }

    @Override
    public Result publish(KKonwledgeVo kKonwledgeVo) {
        UUserDto uUserDto = BaseContext.get();

        KKonwledge kKonwledge = new KKonwledge();
        kKonwledge.setTitle(kKonwledgeVo.getTitle());
        kKonwledge.setContent(kKonwledgeVo.getContent());
        kKonwledge.setPic(kKonwledgeVo.getPic());

        kKonwledge.setUserId(uUserDto.getId());

        this.save(kKonwledge);

        return Result.ok(kKonwledge);
    }

    @Override
    public Result hot() {

        //先走redis
        String key = "hot_list";
        List<KKonwledge> collect = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, 8).stream().map((item) -> {
            Long value = Long.parseLong((String) item.getValue());
            KKonwledge one = this.getById(value);
            return one;
        }).collect(Collectors.toList());

        if (collect==null || collect.size()==0){
            Page<KKonwledge> page = new Page<>(1, 8);

            LambdaQueryWrapper<KKonwledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.orderByDesc(KKonwledge::getUpdateTime);

            this.page(page, lambdaQueryWrapper);
            return Result.ok(page.getRecords());
        }
        return Result.ok(collect);
    }

    @Override
    public Result getOneByID(Long id) {

        //获取文章详细信息
        KKonwledge one = this.getOne(new LambdaQueryWrapper<KKonwledge>().eq(KKonwledge::getId, id));
        if (one == null){
            return Result.fail("没有该知识");
        }

        //获取文章评论信息
        List<KRemarkDto> remarks = remarkService.getRemarkByKnowledgeID(id).stream().map((item) -> {
            Long userId = item.getUserId();
            UUser byId = iuUserService.getById(userId);
            UUserDto uUserDto = new UUserDto();
            BeanUtils.copyProperties(byId, uUserDto);
            KRemarkDto kRemarkDto = new KRemarkDto();
            BeanUtils.copyProperties(item, kRemarkDto);
            kRemarkDto.setAuthor(uUserDto);
            return kRemarkDto;
        }).collect(Collectors.toList());

        //组装dto
        KKonwledgeDto kKonwledgeDto = new KKonwledgeDto();
        BeanUtils.copyProperties(one,kKonwledgeDto);

        UExpert author = iuExpertService.getOne(new LambdaQueryWrapper<UExpert>().eq(UExpert::getUserId, one.getUserId()));
        kKonwledgeDto.setAuthor(author);
        kKonwledgeDto.setRemarks(remarks);

        //返回结果
        return Result.ok(kKonwledgeDto);
    }

    @Override
    public Result delete(Long id) {

        this.removeById(id);

        return Result.ok("删除成功");
    }

    @Override
    public Result users() {

        Long userId = BaseContext.get().getId();

        LambdaQueryWrapper<KKonwledge> lambdaQueryWrapper = new LambdaQueryWrapper<KKonwledge>().eq(KKonwledge::getUserId, userId);

        List<KKonwledge> list = this.list(lambdaQueryWrapper);

        return Result.ok(list);
    }

}
